from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select(".details")

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li.select(".list-details-hearder a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = 'http://taav3.wkinfo.com.cn'+li.select(".list-details-hearder a")[0]["href"]
        except:
            pass
        try:
            tempData["summary"] = li.select(".list-details-info")[0].text.strip().replace('[English]','').replace('[中英对照]','');
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://lawv3.wkinfo.com.cn',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'Referer': 'http://lawv3.wkinfo.com.cn/',
        'Content-Length': '0',
    }

    data = {
        'sp.term': keyword,
        'termField': 'title',
        'accuracy': 'accuracy',
        'mode': 'simple',
        'collection': 'legislation',
        'sp.pageNo': '',
        'sp.order': 'score',
        'reserved_query': '',
        'sp.pageSize': '6',
        'search_form_breadcrumbs': '',
        'search_form_old_breadcrumbs': '',
        'nav_channel': '',
        'hiddenTeaser': '',
        'scope': '',
        'viewType': '',
        'navSelected': 'legislation',
        'searchInResult': 'false',
        'IfSubmit': 'true',
        'isAcc': '',
        'firstA': '',
        'deleteTerm': '',
        'searchReturn': '',
        'searchOptions': '',
        'isToList': '',
        'legislationSummary': '',
        'advancedSearchHasBody': '',
        'groupingField': 'levelEffect',
        'searchType': 'ajax',
        'orderSpec': '1',
        'searchCode': '0'
    }

    response = requests.post('http://lawv3.wkinfo.com.cn/search/process', headers=headers, data=data)

    allData = formData(response)

    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")